const { typeTable } = require('../../schemas/index');

const { getResJson,formatTime } = require('../../assets/util');

/**
 * 添加类型
 * @param {Object} params 参数
 * @param {Function} callback 
 */
exports.addType = (params, callback) => {
    typeTable.findOne({ typeName: params.typeName }, (err, typeData) => {
        if (typeData) {
            let resJson = getResJson(typeData,'请求失败,类型名重复！', false);
            callback(resJson);
            return
        }
        params.date = formatTime();
        params.articleTotal = 0;
        typeTable.create(params, (err, data) => {
            let resJson = {};
            if (err) {
                resJson = getResJson(data,'添加失败', false);
            } else {
                resJson = getResJson(data,'添加成功');
            }
            callback(resJson);
        })
    })
}

/**
 * 查询类型
 * @param {Function} callback
 */
exports.searchType = (callback) => {
    typeTable.find({}, (err, data) => {
        let resJson = {};
        if (err) {
            resJson = getResJson(data,'查询失败',false);
        } else {
            resJson = getResJson(data,'查询成功');
        }
        callback(resJson);
    })
}

/**
 * 修改类型
 * @param {Object} params 参数
 * @param {Function} callback
 */
exports.editType = (params, callback) => {
    typeTable.update({ '_id': params._id }, { $set: { 'typeName': params.typeName } }, (err, data) => {
        let resJson = {};
        if (err) {
            resJson = getResJson(data,'修改失败',false);
        } else {
            resJson = getResJson(data,'修改成功');
        }
        callback(resJson);
    })
}

/**
 * 删除类型
 */
exports.deleteType = (params, callback) => {
    typeTable.deleteOne({'_id':params._id},(err,data) => {
        let resJson = {};
        if (err) {
            resJson = getResJson(data,'删除失败',false);
        } else {
            resJson = getResJson(data,'删除成功');
        }
        callback(resJson);
    })
}